<template>
  <BaseForm v-model="formDataModel" @close="$emit('callBack')" />
</template>

<script lang="tsx" setup>
import type { FormInstance } from 'element-plus'
import PurchaseOrderInfoDetailApi from '/@/api/webPath/PurchaseOrderInfoDetailApi.ts';
import { translate } from "/@/i18n";
import FORM_FIELD_TYPE from "/@/constants/FormFieldType.ts";
import { computed, ref, onMounted, toRaw, defineProps, defineEmits, defineExpose } from 'vue';
import PurchaseOrderInfoApi from '~/src/api/webPath/PurchaseOrderInfoApi';

defineOptions({
  name: 'PurchaseOrderInfoDetailEdit',
})
const props = defineProps({
  modelValue: {

  }
})
const emit = defineEmits(['fetch-data', 'callBack'])

const formRef = ref<FormInstance>();
const title = ref<string>('');
const dialogFormVisible = ref<boolean>(false);

const supplierTypeList = ref()
const supplierList = ref([])

const canCiTypeList = ref()
function getCANciTypeList() {
  PurchaseOrderInfoDetailApi.getCanciTypeList().then(res => {
    console.log(1111111111111111, res.data);
    canCiTypeList.value = res.data.map(item => ({ label: item.dicClassTypeName, value: item.dicClassType }))
    console.log("canCiTypeList", canCiTypeList.value)
  })
}

function getSupplierTypeList() {
  PurchaseOrderInfoDetailApi.getSupplierTypeList().then(res => {
    console.log("供应商类型", res.data);
    supplierTypeList.value = res.data.map(item => ({ label: item.name, value: item.name }))
    console.log("供应商烈性2", supplierTypeList.value)
  })
}



// async function remoteSearch(query: string) {
//   // TODO 更换为全量搜索基础供应商列表
//   const data = (await PurchaseOrderInfoDetailApi.getPageDatas({ supplierName: query })).data.records
//   console.log("search data:", data);
//   supplierList.value = data
//   const options = data.map(item => ({
//     label: item.supplierName,
//     value: item.supplierName
//   }))
//   console.log("options11111", options)
//   return options
// }

// function updateForm(id: any, updateParam: (key: any, value: any) => void) {
//   console.log("update 111111 ids:", id)
//   console.log("param 111111", updateParam)
//   const supplier = supplierTypeList.value.find(x => x.id === id)
//   console.log("current supplier", supplier)
//   for (const key of Object.keys(toRaw(supplier))) {
//     for (const { field } of formDataModel.value.items) {
//       if (key === field) {
//         updateParam(key, supplier[key])
//       }
//     }
//   }
// }

const num = ref(0)
const Price = ref(0)
const tableData = ref<any[]>([])
const totalPrice = computed(() => {
  return num.value * Price.value
})

const formDataModel = ref({
  columnCount: 1,
  expandLimit: 6,
  autoFit: false,
  columnWidth: '300px',
  labelPosition: 'right',
  labelWidth: '100px',
  modelData: {},  //表单参数值 初始化
  callback: async (any: object) => {  //表单执功后回调
    //完成数据提交
    for (const item of formDataModel.value.items) {
      if (item.multiple === true) {
        any[item.field] = any[item.field].join()
      }
    }
    // const response = await PurchaseOrderInfoDetailApi.save(any);
    // // const { message } = await PurchaseOrderInfoDetailApi.save(any) 
    // console.log("PurchaseOrderInfoDetailApi.save response:", response);
    // const { message } = response;
    // 编辑
    if (props.modelValue.query.purchaseOrderInfoId) {
      const { list } = any
      list.forEach(x => {
        x.orderId = props.modelValue.query.purchaseOrderInfoId
      })
      console.log("list", list)
      const response = await PurchaseOrderInfoDetailApi.batchSave(list);
      const message = response?.data?.message || response?.message || '操作成功';
      $baseMessage(message, 'success', 'vab-hey-message-success');
      dialogFormVisible.value = false
      // 新增
    } else {
      const list = any.list.map(x => {
        const { supplierName, ...rest } = x
        return {
          supplier: supplierName,
          ...rest
        }
      })
      const response = await PurchaseOrderInfoApi.batchSave({ list });
      const message = response?.data?.message || response?.message || '操作成功';
      $baseMessage(message, 'success', 'vab-hey-message-success');
      dialogFormVisible.value = false
    }

    //事件及数据推送到上一层父类
    emit('callBack', any); //把表单数据推送到上一层
  },
  items: [  //表单item数据初始化
    {
      field: "list",
      type: FORM_FIELD_TYPE.EDITABLETABLE,
      modelData: {
        data: tableData,
        delApi: PurchaseOrderInfoDetailApi.del,
        delParamKey: 'purchaseOrderInfoDetailIds',
        columns: [
          {
            label: "采购日期",
            width: "180px",
            field: "purchaseDate",
            type: FORM_FIELD_TYPE.DATE,
            defaultValue: `${new Date().getFullYear()}-${(new Date().getMonth() + 1).toString().padStart(2, '0')}-${(new Date().getDate()).toString().padStart(2, '0')}`,
            rule: [
              {
                required: true,
                message: "请输选择采购日期"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "供应商类型",
            field: "supplierTypeName",
            clearable: true,
            width: "200px",
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            // defaultValue: '元',
            options: supplierTypeList,
            placeholder: "请输入",
            callback: async (v) => {
              const data = await PurchaseOrderInfoDetailApi.getPageDatas({ supplierTypeName: v })
              if (data) {
                const { data: { records } } = data
                supplierList.value = records.map(item => ({
                  label: item.supplierName,
                  value: item.supplierName
                }
                ))
                console.log("supplierList", supplierList.value)
              }
            },
            rule: [
              {
                required: true,
                message: "请选择供应商类型"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "供应商名称",
            field: "supplierName",
            clearable: true,
            width: "200px",
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            options: supplierList,
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请选择供应商"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "餐次",
            field: "mealTimes",
            clearable: true,
            type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
            options: canCiTypeList,
            width: "150px",
            placeholder: "请输入",
            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },

            },

          },
          {
            label: "班组",
            field: "teamsGroups",
            width: "150px",
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            placeholder: "请输入",
            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },
          },
          {
            label: "食材名称",
            field: "foodName",
            width: "150px",
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            placeholder: "请输入",
            // rule: {
            //   trigger: 'blur',
            //   validator: (rule: any, value: any, callback: any) => {  //绑定验证
            //     callback();
            //   },
            // },
            rule: [
              {
                required: true,
                message: "请输入食材名称"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "预估采购量",
            field: "num",
            width: "180px",
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            placeholder: "请输入",
            callback: (handlers, formData, value: any) => {
              if (formData["unitPrice"]) {
                handlers.updateParam("totalPrice", +value * +formData["unitPrice"])
              }
            },
            rule: [
              {
                required: true,
                message: "请输入采购数量"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]

          },
          {
            label: "单位",
            field: "unit",
            clearable: true,
            width: "150px",
            type: FORM_FIELD_TYPE.INPUT,
            defaultValue: '公斤',
            placeholder: "请输入",

            rule: [
              {
                required: true,
                message: "请输入单位"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]

          },
          {
            label: "单价",
            field: "unitPrice",
            clearable: true,
            type: FORM_FIELD_TYPE.INPUT,
            width: "100px",
            placeholder: "请输入",
            callback: (handlers, formData, value: any) => {
              if (formData["num"]) {
                handlers.updateParam("totalPrice", +value * +formData["num"])
              }
            },
            rule: [
              {
                required: true,
                message: "请输入单价"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "单价单位",
            field: "priceUnit",
            clearable: true,
            width: "120px",
            type: FORM_FIELD_TYPE.INPUT,
            defaultValue: '公斤/元',
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请输入单价单位"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },
          {
            label: "总价",
            field: "totalPrice",
            clearable: true,
            width: "100px",
            type: FORM_FIELD_TYPE.INPUT,
            config: {
              disabled: true,
            },
            placeholder: "自动计算",

            // value: totalPrice.value,

            rule: {
              trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {  //绑定验证
                callback();
              },
            },

          },
          {
            label: "总价单位",
            field: "totalPriceUnit",
            clearable: true,
            width: "120px",
            type: FORM_FIELD_TYPE.INPUT,
            defaultValue: '元',
            placeholder: "请输入",
            rule: [
              {
                required: true,
                message: "请输入总价单位"
              },
              {
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {  //绑定验证
                  callback();
                },
              },
            ]
          },


        ]

      }
    },
  ],
})

//页面数据加载
onMounted(async () => {
  getCANciTypeList()
  getSupplierTypeList()
  //初始化数据model
  if (props.modelValue.query) { //跳转过来时候有参数
    if (props.modelValue.query.purchaseOrderInfoId) {  //id存在则为编辑，加载网络数据，如上级页面带参数手动覆盖

      const res = await PurchaseOrderInfoApi.getDetail({
        purchaseOrderInfoId: props.modelValue.query.purchaseOrderInfoId   //从路由中获取参数
      })
      formDataModel.value.modelData = res;

      const detailRes = await PurchaseOrderInfoDetailApi.getPageData({
        orderId: props.modelValue.query.purchaseOrderInfoId,   //从路由中获取参数
        _size: 1000,
      })
      if (detailRes) {
        tableData.value = detailRes.data.records
      }
    } else {
      //新增时候则用父类页面传参默认填充可根据业务修改
      for (const key in props.modelValue.query) {
        formDataModel.value.modelData[key] = props.modelValue.query[key]
      }
    }
  }
})


//方法暴露区域  todo
defineExpose({

})

</script>
